package com.he.ymw.controller;

import com.he.ymw.pojo.BuyCar;
import com.he.ymw.pojo.User;
import com.he.ymw.service.BuyCarService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 处理购物车操作的类
 */
@Controller
public class BuyCarController {


    @Resource
    BuyCarService buyCarService;

    @RequestMapping("/toBuyCar")
    public String toBrandList(HttpSession session, Model model) {
        // 根据用户id去查询购物车
        User user = (User) session.getAttribute("user");
        // 将用户的购物车数据返回前端交互
        model.addAttribute("buyCars",buyCarService.findBuyCarAll(user.getId()));
        return "BuyCar";
    }

    /**
     * 加入购物车
     */
    @RequestMapping("/addBuyCar")
    @ResponseBody
    public Boolean addBuyCar(Integer proId,Integer cost,HttpSession session) {
        // 加入购物车
        return buyCarService.addBuyCar(
                // id:数据库自增，为了不报错随便填，quantity:默认加入一件商品
                new BuyCar(0,((User) session.getAttribute("user")).getId(), proId,cost,1)) > 0;
    }

    /**
     * 添加商品数量
     */
    @RequestMapping("/addGoodsQuantity")
    @ResponseBody
    public Boolean AddGoodsQuantity(
            @RequestParam("id") Integer id,
            @RequestParam("cost") Integer cost,
            @RequestParam("quantity") Integer quantity) {
        // 每点击一次数量++
        ++quantity;
        // 获取数据库商品的价格，
        cost = quantity * buyCarService.findPrice(id);
        // 修改数据库
        return buyCarService.addGoodsQuantity(id,cost,quantity);
    }

    /**
     * 扣除商品数量
     */
    @RequestMapping("/deductionGoodsQuantity")
    @ResponseBody
    public Boolean DeductionGoodsQuantity(
            @RequestParam("id") Integer id,
            @RequestParam("cost") Integer cost,
            @RequestParam("quantity") Integer quantity) {
        if (quantity == 1) {
            return true;
        } else {
            // 每点击一次数量++
            --quantity;
            // 获取数据库商品的价格，计算--后的总价格
            cost -= buyCarService.findPrice(id);
            // 修改数据库
            return buyCarService.addGoodsQuantity(id,cost,quantity);
        }

    }





}
